/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */
package com.andy.eqm.server.socket.codec;

import java.util.List;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

/**
 * cuiwm
 */
public class ResponseEncoder extends MessageToMessageEncoder<IWrite> {

	private static final Logger logger = Logger.getLogger(ResponseEncoder.class);
	
	@Override
	protected void encode(ChannelHandlerContext ctx, IWrite msg, List<Object> out) throws Exception {
		if (msg == null) {
            return;
        }
		
		if (logger.isInfoEnabled())logger.info("发包CmdId：" + msg.getCmd());
		try {
			byte[] src = msg.getByteArray();
			ByteBuf ib = null;
			if(src != null){
				ib = Unpooled.wrappedBuffer(src);
			}else{
				ib = Unpooled.buffer(1024);
				ib.writeInt(0); // 占位
				msg.write(ib);
				ib.setInt(0, ib.readableBytes()-4); // 更新长度
				src = new byte[ib.readableBytes()];
				ib.getBytes(0, src);
				msg.setByteArray(src);
			}
			out.add(ib);
		} catch (Exception e) {
			logger.error("编码异常", e);
		}
    	
	}
    
}
